package com.kyh.util;

import java.security.MessageDigest;
import java.util.Map;
import java.util.TreeMap;

public class SignUtil {

	/**
	 * 获取签名值，签名方式：自动剔除掉null或“”的参数，按照ASCII升序排列，以param1=value1&param2=value2...&key=keyvalue的方式，加密转大写
	 * @param paramMap 参数值
	 * @param key key值
	 * @return
	 */
	public static String createMd5Sign(Map<String, String> paramMap, String key) {

		String sign = encodeByMd5(getStrForSign(paramMap, key)).toUpperCase();
//		System.out.println("签名后的字符串---" + sign);

		return sign;
	}

	private static String getStrForSign(Map<String, String> paramMap, String key) {

		Map<String, String> treeMap = new TreeMap<String, String>();

		for (String mapkey : paramMap.keySet()) {
			String mapvalue = paramMap.get(mapkey);
			if (mapvalue == null || mapvalue.length() == 0) {
				continue;
			} else {
				treeMap.put(mapkey, mapvalue);
			}
		}

		StringBuffer sbForSign = new StringBuffer("");
		for (String mapkey : treeMap.keySet()) {
			sbForSign.append(mapkey + "=" + treeMap.get(mapkey) + "&");
		}
		
		sbForSign.append("key=" + key);

		String StrForSign = sbForSign.toString();
//		System.out.println("签名前拼接的字符串---" + StrForSign);
		return StrForSign;
	}

	/** 对字符串进行MD5加密后转大写 */
	private static String encodeByMd5(String originString) {
		if (originString != null) {
			try {
				MessageDigest mdInst = MessageDigest.getInstance("MD5");
				mdInst.update(originString.getBytes("UTF-8"));
				byte[] arr = mdInst.digest();
				StringBuffer sb = new StringBuffer();
				for (int i = 0; i < arr.length; ++i) {
					sb.append(Integer.toHexString((arr[i] & 0xFF) | 0x100).substring(1, 3));
				}
				return sb.toString();
			} catch (Exception e) {
				return e.toString();
			}
		}
		return null;
	}
}
